/******************************************************************************
File: OperBO.java

Version 1.0
Date            Author                Changes
Jan.20,2005     PO tools              Created

Copyright (c) 2003, Vanda Group.
all rights reserved.
******************************************************************************/
package com.vandagroup.portal.oper;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import com.vandagroup.common.bean.BaseBean;
import com.vandagroup.common.bo.ESSBO;
import com.vandagroup.common.bo.UserContext;
import com.vandagroup.common.po.ESSTransaction;
import com.vandagroup.common.resources.SysPara;
import com.vandagroup.common.util.Result;
import com.vandagroup.common.util.SQLFormat;
import com.vandagroup.common.util.SQLUtility;
import MD5.Crypt;
import com.vandagroup.portal.PortalParas;

//import com.vandagroup.common.bean.BaseBean;
/**
* This class is the Business Process Object interface
* 
* @see ess.base.bo.ESSBO
*/
public class OperBO extends ESSBO {
	OperPO po = new OperPO();

	/**
	 * d ����ָ����Oper����
	 */
	public String add(OperFormBean bean) throws SQLException, Exception {
		if (bean.getLoginID().toUpperCase().indexOf("ADMIN") != -1) {
			throw new Exception("��ӵĲ���T��䛴�a���ܰ�admin���ִ������ִ���ϵ�y�����ִ���");
		}
		if (bean.getLoginID().toUpperCase().indexOf("CUST") != -1) {
			throw new Exception("��ӵĲ���T��䛴�a���ܰ�cust���ִ������ִ���ϵ�y�����ִ���");
		}
		// System.out.println("SELECT COUNT(*) COUNT FROM OPER WHERE LOGINID =
		// '" + bean.getLoginID() + "'");
		BaseBean baseBean = po
				.queryBean("SELECT COUNT(*) COUNT FROM OPER WHERE LOGINID = '"
						+ bean.getLoginID() + "'");
		if (baseBean != null
				&& ((BigDecimal) baseBean.get("COUNT")).intValue() != 0) {
			throw new Exception("��ӵĲ���T��䛴�a�ѽ����ڣ�");
		}
		return addOper(bean);
	}

	public String addCust(OperFormBean bean) throws SQLException, Exception {
		bean.setLoginID("CUST" + bean.getLoginID());
		return addOper(bean);
	}

	private String addOper(OperFormBean bean) throws SQLException, Exception {
		ESSTransaction trans = new ESSTransaction();
		trans.begin();
		String operID = bean.getLoginID();
		bean.setOperID(operID);

		String md5Password = (new Crypt()).EnCrypt(bean.getPassword()) ;
		bean.setPassword(md5Password);
		po.setOperForm(bean);
		int rows = trans.add(po);
		if (bean.getRoleID() != null && bean.getRoleID().length != 0) {
			rows += trans
					.executeUpdate("INSERT INTO OPERROLE ( OPERID, ROLEID ) SELECT '"
							+ operID
							+ "', ROLEID FROM ROLE WHERE ROLEID IN ("
							+ SQLFormat.joinAsList(bean.getRoleID(), true)
							+ ")");
		}
		trans.commit();
		return operID;
	}

	/**
	 * �h��ָ����Oper����
	 */
	public int remove(String ids[]) throws SQLException, Exception {
		ESSTransaction trans = new ESSTransaction();
		trans.begin();
		String whereClause = "";
		List admins = this.getAdminOpersID();
		for (int i = 0; i < ids.length; i++) {
		    Iterator it = admins.iterator();
		    while(it.hasNext()) {
		        if(ids[i].equals(it.next().toString())) {
		            throw new Exception("�h��Ĳ���T��䛴�a���ܰ�admin���ִ������ִ���ϵ�y�����ִ���");
		        }
		    }			
			if (!whereClause.equals(""))
				whereClause += " or ";
			whereClause += "OPERID='" + ids[i].split(",")[0] + "'";
		}
		po.setWhereClause(whereClause);
				
		// �h���c֮�P�Ľ�ɫ�P�� operrole���е��Y��
		int rows = trans.executeUpdate("delete from operrole where operid in ("
				+ SQLFormat.joinAsList(ids, true) + ")");
		//int rows = po.delete();
		rows += trans.delete(po);
		trans.commit();
		return rows;
	}

	/**
	 * �@ȡָ���l����Oper���
	 */
	public Result query(int pageNO, OperFormBean bean, String childOrgIDs)
			throws SQLException, Exception {
		String whereClause = "";
		Object operID = bean.getOperID();
		//Object orgID = bean.getOrgID();
		Object loginID = bean.getLoginID();
		Object operName = bean.getOperName();
		//Object password = (new Crypt()).EnCrypt(bean.getPassword());
		//Object operType = bean.getOperType();
		//Object channel = bean.getChannel();
		//Object channelCode = bean.getChannelCode();
		Object status = bean.getStatus();
		//Object sysType = bean.getSysType();
		//Object language = bean.getLanguage();
		whereClause = " 1=1 ";
		whereClause = SQLUtility.addLikeClause(whereClause, "OPERID", operID);
		whereClause = SQLUtility.addLikeClause(whereClause, "LOGINID", loginID);
		whereClause = SQLUtility.addLikeClause(whereClause, "OPERNAME",
				operName);
		whereClause = SQLUtility.addLikeClause(whereClause, "status", status);
		if (whereClause == null || whereClause.equals(""))
			whereClause = "";
		if (childOrgIDs.length() > 0) {
			whereClause = whereClause + " and ORGID in (" + childOrgIDs + ")";
		}
		po.setWhereClause(whereClause);
		// System.out.println(po.getSql());
		po.setOrderBy("OPERID");
		po.setResultPage(Result.DEFAULT_PAGE_SIZE, pageNO);
		Result result = po.queryResult();
		return result;
	}

	/**
	 * �_��Oper�����form
	 */
	public OperFormBean retrieveForm(OperFormBean bean) throws SQLException {
		String whereClause = "";
		Object operID = bean.getOperID();
		whereClause = SQLUtility.addWhereClauseKey(whereClause, "OPERID",
				operID);
		po.setWhereClause(whereClause);
		return (OperFormBean) po.retrieveForm();
	}

	/**
	 * ����ָ����Oper����
	 */
	public int update(OperFormBean bean) throws SQLException, Exception {
		ESSTransaction trans = new ESSTransaction();
		trans.begin();
		bean.setLanguage(SysPara.LANGUAGE_COMPLEX);
		if(!bean.getStatus().equals(SysPara.STATUS_DISABLE) && !bean.getStatus().equals(SysPara.STATUS_ENABLE)){
		    bean.setStatus(SysPara.STATUS_ENABLE);
		}
		bean.setSysType(SysPara.SYSTEM_PORTAL);
		bean.setOperType(SysPara.OPRTYPE_WORKER);
		po.setWhereClause("OPERID='" + bean.getOperID() + "'");
		po.setOperForm(bean);
		if (bean.getOldpassword().equals("edit")) {
			bean.setPassword(bean.getPassword());
		}
		int rows = trans.update(po);
		trans.executeUpdate("DELETE FROM OPERROLE WHERE OPERID = '"
				+ bean.getOperID() + "'");
		if (bean.getRoleID() != null && bean.getRoleID().length != 0) {
			rows += trans
					.executeUpdate("INSERT INTO OPERROLE ( OPERID, ROLEID ) SELECT '"
							+ bean.getOperID()
							+ "', ROLEID FROM ROLE WHERE ROLEID IN ("
							+ SQLFormat.joinAsList(bean.getRoleID(), true)
							+ ")");
		}
		trans.commit();
		return rows;
	}

	/**
	 * ����ָ�������в���T��orgid
	 */
	public int updateOrgid(OperFormBean bean) throws SQLException {
		String sql = "update OPER set ORGID='" + bean.getOrgID()
				+ "' WHERE OPERID='" + bean.getOperID() + "'";
		return po.executeUpdate(sql);
	}

	/**
	 * ����C����aȡ�˙C�����õĲ��T
	 * 
	 * @param user
	 * @return HashMap
	 * @throws SQLException
	 * @throws Exception
	 *             Create Date : 2004-2-11
	 */
	public HashMap getDepts(UserContext user) throws SQLException, Exception {
		HashMap depts = new HashMap();
		BaseBean[] beans = po
				.query("SELECT DEPTID, DEPTNAME FROM DEPT WHERE DEPTID IN ( SELECT DEPTID FROM ORGDEPT WHERE ORGID = '"
						+ user.getOrgID()
						+ "' AND STATUS = '"
						+ PortalParas.STATUS_VALID + "' )");
		for (int i = 0; beans != null && beans.length != 0 && i < beans.length; i++) {
			depts.put(beans[i].get("DEPTID"), beans[i].get("DEPTNAME"));
		}
		return depts;
	}

	/**
	 * ����C����aȡ�˙C���Y�Ĳ���T
	 * 
	 * @param user
	 * @return HashMap
	 * @throws SQLException
	 * @throws Exception
	 *             Create Date : 2004-2-11
	 */
	public HashMap getOpers(UserContext user) throws SQLException, Exception {
		HashMap opers = new HashMap();
		BaseBean[] beans = po
				.query("SELECT OPERID, OPERNAME FROM OPER WHERE ORGID = '"
						+ user.getOrgID() + "' AND STATUS = '"
						+ PortalParas.STATUS_VALID + "'");
		for (int i = 0; beans != null && beans.length != 0 && i < beans.length; i++) {
			opers.put(beans[i].get("OPERID"), beans[i].get("OPERNAME"));
		}
		return opers;
	}

	/**
	 * ����C����aȡ�˙C���µĿ��ý�ɫ
	 * 
	 * @param user
	 * @return HashMap
	 * @throws SQLException
	 * @throws Exception
	 *             Create Date : 2004-2-11
	 */
	public HashMap getRoles(String orgID) throws SQLException, Exception {
		HashMap roles = new HashMap();
		String sql = "SELECT ROLEID, ROLENAME FROM ROLE WHERE ROLEID IN ( SELECT ROLEID FROM ORGROLE WHERE ORGID = '"
				+ orgID + "' AND STATUS = '" + PortalParas.STATUS_VALID + "' )";
		BaseBean[] beans = po.query(sql);
		for (int i = 0; beans != null && beans.length != 0 && i < beans.length; i++) {
			roles.put(beans[i].get("ROLEID"), beans[i].get("ROLENAME"));
		}
		return roles;
	}

	/**
	 * 
	 * �f��ȡ�����еęC����a �������ڣ�2004-3-25 18:05:36
	 * 
	 * @author ���Ǆ�
	 * @return HashMap
	 * @throws SQLException
	 * @throws Exception
	 */
	public HashMap getOrgs() throws SQLException, Exception {
		HashMap orgs = new HashMap();
		BaseBean[] beans = po
				.query("SELECT ORGID,ORGNAME FROM ORG WHERE STATUS='1'");
		for (int i = 0; beans != null && beans.length != 0 && i < beans.length; i++) {
			orgs.put(beans[i].get("ORGID"), beans[i].get("ORGNAME"));
		}
		return orgs;
	}

	/**
	 * ����C����aȡ�˙C���µĿ��ý�ɫ
	 * 
	 * @param user
	 * @return HashMap
	 * @throws SQLException
	 * @throws Exception
	 *             Create Date : 2004-2-11
	 */
	public HashSet getSelRoles(OperFormBean bean) throws SQLException,
			Exception {
		HashSet roles = new HashSet();
		BaseBean[] beans = po
				.query("SELECT ROLEID FROM OPERROLE WHERE OPERID = '"
						+ bean.getOperID() + "'");
		for (int i = 0; beans != null && beans.length != 0 && i < beans.length; i++) {
			roles.add(beans[i].get("ROLEID"));
		}
		return roles;
	}

	/**
	 * �Д����T��a�Ƿ���Ч
	 * 
	 * @param loginID
	 *            ����T��a
	 * @param password
	 *            �ܴa
	 * @return
	 * @throws Exception
	 */
	public boolean isPasswordValid(String loginID, String password)
			throws Exception {
		String sql = "SELECT OPERID,PASSWORD FROM OPER WHERE LOGINID = '"
				+ loginID + "'";
		// System.out.println(sql);
		BaseBean baseBean = po.queryBean(sql);
		// System.out.println(dataencry.getCorePasswd(password, "password"));

		boolean isValidPassword = (new Crypt()).CheckCrypt((String)baseBean.get("PASSWORD"),password) ;
		if (baseBean != null && isValidPassword) {
			return (true);
		}
		return (false);
	}

	/**
	 * �Д����T��a�������ܴa�Ƿ���Ч
	 * 
	 * @param loginID
	 *            ����T��a
	 * @param password
	 *            �ܴa
	 * @return
	 * @throws Exception
	 */
	public boolean isTransPasswordValid(String loginID, String password)
			throws Exception {
		String sql = "SELECT OPERID,TRANSPASS FROM OPER WHERE LOGINID = '"
				+ loginID + "'";
		// System.out.println(sql);
		BaseBean baseBean = po.queryBean(sql);
		// System.out.println(dataencry.getCorePasswd(password,"password"));

		String md5Password = (new Crypt()).EnCrypt(password) ;
		if (baseBean != null && baseBean.get("TRANSPASS").equals(md5Password)) {
			return (true);
		}
		return (false);
	}

	/**
	 * 取得登录的类型
	 * 
	 * @param loginID 
	 * @param password 未加密的密码
	 * @return
	 */
	public String getLoginType(String loginID, String password)	throws Exception {
		String sql = "SELECT OPERID,PASSWORD,OPERTYPE FROM OPER WHERE LOGINID = '"
				+ loginID + "'";
		// System.out.println(sql);
		BaseBean baseBean = po.queryBean(sql);
		
		boolean validPassword = (new Crypt()).CheckCrypt((String)baseBean.get("PASSWORD"), password) ;
		
		if (baseBean != null && validPassword) {
			return ((String) baseBean.get("OPERTYPE"));
		}
		return (null);
	}

	/**
	 * �������T��aȡԓ����T�����Ľ�ɫ�YӍ
	 * 
	 * @param operID
	 * @return String[][]
	 * @throws Exception
	 *             Create Date : 2004-2-10
	 */
	public String[][] getOperRoles(String operID) throws Exception {
		String[][] roles = null;
		BaseBean[] beans = po
				.query("SELECT ROLEID, ROLENAME FROM ROLE WHERE ROLEID IN ( SELECT ROLEID FROM OPERROLE WHERE OPERID = '"
						+ operID + "' )");
		if (beans != null && beans.length != 0) {
			roles = new String[beans.length][];
			for (int i = 0; i < beans.length; i++) {
				roles[i] = new String[2];
				roles[i][0] = (String) beans[i].get("ROLEID");
				roles[i][1] = (String) beans[i].get("ROLENAME");
			}
		}
		return roles;
	}

	/**
	 * �������T��䛴�a���@�ò���T�YӍ
	 * 
	 * @param operID
	 *            ����T��a
	 * @return ����T�YӍ
	 * @throws SQLException
	 */
	public OperFormBean getOperInfo(String loginID) throws SQLException {
		po.setWhereClause("LOGINID='" + loginID + "'");
		return (OperFormBean) po.retrieveForm();
	}

	/**
	 * �������T��a�@�ò���T��Q
	 * 
	 * @param operID
	 *            ����T��a
	 * @return ����T��Q
	 * @throws Exception
	 */
	public String getOperName(String operID) throws Exception {
		if (operID == null || operID.trim().equals("")) {
			throw (new Exception("����T��a�oЧ"));
		}
		OperFormBean bean = new OperFormBean();
		bean.setOperID(operID);
		OperFormBean form = retrieveForm(bean);
		return (form.getOperName());
	}

	/**
	 * ����ָ����UpdatePwd����
	 */
	public int updatePwd(OperFormBean bean) throws SQLException, Exception {
		String whereClause = "";
		String ifok = "NO";
		OperPO po = new OperPO();
		OperBO oper = new OperBO();
		boolean succ = oper.isPasswordValid(bean.getLoginID(), bean
				.getPassword());
		if (!succ) {
			throw new Exception("你输入的旧密码不正确！");
		} else {
			ifok = "YES";
		}
		bean.setIfok(ifok);

		String md5Password = (new Crypt()).EnCrypt(bean.getPassword()) ;
		bean.setPassword(md5Password);
		po.setWhereClause("LOGINID='" + bean.getLoginID() + "' ");

		md5Password = (new Crypt()).EnCrypt(bean.getNewPassword()) ;
		int rows = po.update("password", md5Password);
		return rows;
	}
	/**
	 * ȡ������LoginID�а�admin�ִ���OPERID
	 * @return һ��Ԫ�؞�OPERID��List
	 * @throws SQLException
	 * @throws Exception
	 */
	public List getAdminOpersID() throws SQLException, Exception{
	    List admins = new ArrayList();
	    BaseBean[] beans = po
			.query("SELECT OPERID FROM OPER WHERE LOGINID LIKE '%admin%'");				
	    if(beans != null) {
	        for(int i = 0; i < beans.length; i ++) {
	            admins.add(beans[i].get("OPERID").toString());	        
	        }
	    }
	    
	    return admins;
	}
}
